import React, { useState } from 'react';
import { User } from '@/interfaces/user';

interface ProfileEditorProps {
  user: User;
  onSave: (user: User) => void;
}

const ProfileEditor: React.FC<ProfileEditorProps> = ({ user, onSave }) => {
  const [formData, setFormData] = useState({
    name: user.name,
    email: user.email,
    bio: user.bio || '',
    website: user.website || '',
    avatar: user.avatar || ''
  });

  const [isUploading, setIsUploading] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);

  const handleInputChange = (field: keyof typeof formData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    setHasChanges(true);
  };

  const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setIsUploading(true);
    
    try {
      // Simulate file upload
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // Create preview URL
      const previewUrl = URL.createObjectURL(file);
      handleInputChange('avatar', previewUrl);
    } catch (error) {
      console.error('Upload failed:', error);
    } finally {
      setIsUploading(false);
    }
  };

  const handleSave = () => {
    const updatedUser: User = {
      ...user,
      ...formData
    };
    
    onSave(updatedUser);
    setHasChanges(false);
  };

  const handleReset = () => {
    setFormData({
      name: user.name,
      email: user.email,
      bio: user.bio || '',
      website: user.website || '',
      avatar: user.avatar || ''
    });
    setHasChanges(false);
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-xl font-semibold text-ios-gray-900 dark:text-white mb-4">
          Profile Information
        </h2>
        <p className="text-ios-gray-600 dark:text-ios-gray-400 mb-6">
          Update your public profile information
        </p>
      </div>

      {/* Avatar Section */}
      <div className="flex items-start space-x-4">
        <div className="relative">
          <div className="w-20 h-20 rounded-full bg-ios-gray-200 dark:bg-ios-gray-700 overflow-hidden">
            {formData.avatar ? (
              <img 
                src={formData.avatar} 
                alt="Profile" 
                className="w-full h-full object-cover"
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center text-ios-gray-400">
                <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                </svg>
              </div>
            )}
          </div>
          
          {isUploading && (
            <div className="absolute inset-0 bg-black/50 rounded-full flex items-center justify-center">
              <svg className="w-6 h-6 text-white animate-spin" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
            </div>
          )}
        </div>
        
        <div className="flex-1">
          <label className="block">
            <span className="sr-only">Choose profile photo</span>
            <input
              type="file"
              accept="image/*"
              onChange={handleAvatarUpload}
              className="hidden"
              id="avatar-upload"
            />
            <label
              htmlFor="avatar-upload"
              className="cursor-pointer inline-flex items-center px-4 py-2 bg-ios-gray-100 dark:bg-ios-gray-700 hover:bg-ios-gray-200 dark:hover:bg-ios-gray-600 text-ios-gray-700 dark:text-ios-gray-300 rounded-apple-md transition-colors"
            >
              <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
              </svg>
              Upload Photo
            </label>
          </label>
          <p className="text-xs text-ios-gray-500 dark:text-ios-gray-400 mt-1">
            JPG, PNG up to 2MB
          </p>
        </div>
      </div>

      {/* Form Fields */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Name */}
        <div>
          <label className="block text-sm font-medium text-ios-gray-700 dark:text-ios-gray-300 mb-2">
            Full Name
          </label>
          <input
            type="text"
            value={formData.name}
            onChange={(e) => handleInputChange('name', e.target.value)}
            className="w-full px-3 py-2 bg-white dark:bg-ios-gray-700 border border-ios-gray-200 dark:border-ios-gray-600 rounded-apple-md text-ios-gray-900 dark:text-white focus:ring-2 focus:ring-ios-blue focus:border-transparent"
            placeholder="Enter your full name"
          />
        </div>

        {/* Email */}
        <div>
          <label className="block text-sm font-medium text-ios-gray-700 dark:text-ios-gray-300 mb-2">
            Email Address
          </label>
          <input
            type="email"
            value={formData.email}
            onChange={(e) => handleInputChange('email', e.target.value)}
            className="w-full px-3 py-2 bg-white dark:bg-ios-gray-700 border border-ios-gray-200 dark:border-ios-gray-600 rounded-apple-md text-ios-gray-900 dark:text-white focus:ring-2 focus:ring-ios-blue focus:border-transparent"
            placeholder="Enter your email"
          />
        </div>
      </div>

      {/* Website */}
      <div>
        <label className="block text-sm font-medium text-ios-gray-700 dark:text-ios-gray-300 mb-2">
          Website
        </label>
        <input
          type="url"
          value={formData.website}
          onChange={(e) => handleInputChange('website', e.target.value)}
          className="w-full px-3 py-2 bg-white dark:bg-ios-gray-700 border border-ios-gray-200 dark:border-ios-gray-600 rounded-apple-md text-ios-gray-900 dark:text-white focus:ring-2 focus:ring-ios-blue focus:border-transparent"
          placeholder="https://your-website.com"
        />
      </div>

      {/* Bio */}
      <div>
        <label className="block text-sm font-medium text-ios-gray-700 dark:text-ios-gray-300 mb-2">
          Bio
        </label>
        <textarea
          value={formData.bio}
          onChange={(e) => handleInputChange('bio', e.target.value)}
          rows={4}
          className="w-full px-3 py-2 bg-white dark:bg-ios-gray-700 border border-ios-gray-200 dark:border-ios-gray-600 rounded-apple-md text-ios-gray-900 dark:text-white focus:ring-2 focus:ring-ios-blue focus:border-transparent resize-none"
          placeholder="Tell us about yourself..."
        />
        <p className="text-xs text-ios-gray-500 dark:text-ios-gray-400 mt-1">
          {formData.bio.length}/500 characters
        </p>
      </div>

      {/* Action Buttons */}
      {hasChanges && (
        <div className="flex justify-end space-x-3 pt-4 border-t border-ios-gray-200 dark:border-ios-gray-700">
          <button
            onClick={handleReset}
            className="px-4 py-2 text-ios-gray-600 dark:text-ios-gray-400 hover:text-ios-gray-800 dark:hover:text-ios-gray-200 transition-colors"
          >
            Reset
          </button>
          <button
            onClick={handleSave}
            className="px-6 py-2 bg-ios-blue text-white rounded-apple-md hover:bg-ios-blue/90 transition-colors"
          >
            Save Changes
          </button>
        </div>
      )}
    </div>
  );
};

export default ProfileEditor;